
/*
 * This class is responsible for reading the incoming feed from the DCS power meter
 * system. It is also responsible for updating the SPS object,so that the program has
 * an updated knowledge about the power usage of the servers/clusters.
 * 
 * There are 2 probable implementations:
 * 		1. The resource class holds the object of this class, and calls this class whenever a new power consumption is calculated
 * 		2. This class holds objects of the resources, and calls the get powerConsumption method to update it's values.
 */

public class PowerFeedReader implements Runnable,IPowerFeedReader
{
	protected volatile Boolean running = null;
	
	private SystemPowerState sps = null;
	private IServerCluster serverCluster = null;
	private IServerClusterUsageData sC_UsageData = null;	
	
	public PowerFeedReader(SystemPowerState sps, Boolean running, IServerCluster rC, IServerClusterUsageData rC_UsageData) 
	{
		this.sps= sps;
		this.running = running;
		this.serverCluster = rC;
		this.sC_UsageData = rC_UsageData;
	}
	
	public void run()
	{
		while(this.running)
		{
			if(serverCluster.getServerCount() > 0)
			{
				readFeed();
			}
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				System.out.println("Exception in power reader thread sleeping !!");
				e.printStackTrace();
			}
		}
	}
	
	private void readFeed()
	{
		// code to interpret the feed and analyze the individual power usage
		
		if(serverCluster != null)
		{
			for(int i=0;i<serverCluster.getServerCount();i++)
			{
				double temp_pC = serverCluster.getServer(i).getPowerConsumption();	// get the power update for the current resource
				double prevPowerConsump = sps.getValue(i);
				
				if(prevPowerConsump != temp_pC)
				{
					sps.setValue(i, temp_pC);	// update the SPS object
					sC_UsageData.addUsageData(i, new Double(temp_pC));	// update the server usage data object
				}
			}
		}
		
		else
			System.out.println("Error, no server cluster present in power feed reader.");
	}
}
